package com.ydgk.dao;

import com.ydgk.bean.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.List;

public class UserDao extends BaseDao<User> {

    @Override
    public int save(User user) {
        return this.template.update("insert into user values(null,?,?,?,?,?,?,?,?,?)",
                user.getUname(),user.getUpass(),user.getUsex(),user.getUbrith(),user.getUphone(),
                            user.getUadress(), user.getUtype(),user.getMoney(),user.getMoney());
    }

    @Override
    public int updateById(User user) {

        return this.template.update("update user set utype=?,uphone=? where uid=?",
                user.getUtype(),user.getUphone(),user.getUid());
    }

    @Override
    public int deleteById(int id) {
        return this.template.update("delete from user where uid=?",id);
    }

    @Override
    public List<User> findAll() {
        return this.template.query("select * from user",new BeanPropertyRowMapper<User>(User.class));
    }

    @Override
    public User findById(int id) {
        return this.template.queryForObject("select * from user where uid=?",new BeanPropertyRowMapper<>(User.class),id);
    }

    @Override
    public List<User> paging(int pageNumber) {
        return this.template.query("select * from user order by uid desc limit ?,?",new BeanPropertyRowMapper<>(User.class),(pageNumber-1)*pageCount,pageCount);
    }

    public int findByName(String uname){
            List<User> list=this.template.query("select * from user where uname=?",new BeanPropertyRowMapper<>(User.class),uname);
        if(list.size()==0){
            return -1;
        }
        return 1;
    }

    public int  updateMoneyById(User user,int money){
        return this.template.update("update user set money=money- ? where uid=?",money,user.getUid());
    }

    public int selectMoneyById(int id){
        User user=this.template.queryForObject("select * from user where uid=?",new BeanPropertyRowMapper<>(User.class),id);
        if(user!=null){
            return user.getMoney();
        }
        return 0;
    }

    public User login(User user){
        try {
            return this.template.queryForObject("select * from user where uname = ? and upass = ?" ,
                    new BeanPropertyRowMapper<>(User.class),user.getUname(),user.getUpass());
        }catch (Exception e){
            return null ;
        }
    }

    public int total(){
        return this.template.queryForObject("select count(*) from user",Integer.class);
    }

}
